#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Charles.chen
# createDate:2017/9/5
# Title:
# Tip:
from app.toolkit.configSingle import ConfigSingle
import os
import random

# 获取iot-x的只读信息 硬件信息
def getLocalConfig():
    pass

# 从系统配置文件获取用户信息
def getServerConfig():
    configObj = ConfigSingle()
    user_dict = {
        "server_name": configObj.configuration.get("internet_conf", "remote_address"),
        "ip_port": configObj.configuration.get("internet_conf", "ip_port")
    }
    return user_dict


# 从系统配置文件获取用户信息
def getUserConfig():
    configObj = ConfigSingle()
    user_dict = {
        "company_name": configObj.configuration.get("user_conf", "company_name"),
        "company_address": configObj.configuration.get("user_conf", "company_address"),
        "user_name": configObj.configuration.get("user_conf", "user_name"),
        "device_id": configObj.configuration.get("user_conf", "device_id"),
        "device_no": configObj.configuration.get("user_conf", "device_no"),
    }
    return user_dict

# 获取所有的系统只读数据
def getAllSystemConfig():
    configObj = ConfigSingle()
    # ram_info = getRamUsage()

    sys_dict = {
        "unique_id": configObj.configuration.get("system_conf", "unique_id"),
        "cpu": 80,
        "memory_total": 10240,
        "memory_used": 1024,
        "hd_total": 10240,
        "hd_used": 1024,
        "power": "N/A",
        "gps": configObj.configuration.get("system_conf", "gps"),
        "interface": "DB9",
        "upLink_type": "wifi",
        "upTime": 192
    }

    # sys_dict = {
    #     "unique_id": configObj.configuration._get("system_conf", "unique_id"),
    #     "cpu": getCpuFree(),
    #     "memory_total": ram_info["ram_total"],
    #     "memory_used": ram_info["RAM_used"],
    #     "hd_total": getHardDiskTotal(),
    #     "hd_used": getHardDiskUsed(),
    #     "power": "N/A",
    #     "gps": configObj.configuration._get("system_conf", "gps"),
    #     "interface": "DB9",
    #     "upLink_type": "wifi",
    #     "upTime": getRunTime()
    # }
    return sys_dict
    pass

# 获取sd卡容量(单位:M)
def getTFMemory():
    total_size = None
    with os.popen("cd / && df | grep /mnt") as ps:
        strLine = ' '.join(ps.readline().split())
        # 1 最大值 2 已使用值 byte
        res = strLine.split(" ")
        total_size = int(int(res[1])/1024)
    return total_size

# 生成实时配置文件
def generateConfigFile():
    sys_config = {}
    return True
    pass

# 获取系统配置文件备份列表
def getSystemConfigList(path=None):
    fileNames = []
    if path is None:
        return None
    files = os.listdir(path)
    for fl in files:
        if not os.path.isdir(fl):
            fileNames.append(fl.split(".")[0].decode("gbk").encode("utf-8"))
            pass
    return fileNames
    pass

#
def uploadConfig():
    pass

# 修改TF卡存储溢出策略
# TF卡存储溢出策略 0：暂停存储 1：循环覆盖
def updateStorageMethod(menthod=0):
    configObj = ConfigSingle()
    configObj.configuration.set("system_conf", "storage_method", menthod)
    configObj.flushConfig()
    pass


# Return RAM information (unit=kb) in a list
# Index 0: total RAM
# Index 1: used RAM
# Index 2: free RAM
def getRAMinfo():
    p = os.popen('free')
    i = 0
    while 1:
        i = i + 1
        line = p.readline()
        if i == 2:
            return(line.split()[1:4])

# 获取内存使用率 %
def getRamUsage():
    RAM_stats = getRAMinfo()
    RAM_total = round(int(RAM_stats[0]) / 1000, 1)
    RAM_used = round(int(RAM_stats[1]) / 1000, 1)
    # RAM_free = round(int(RAM_stats[2]) / 1000, 1)  # Disk information
    RAM_usage = round(float(RAM_used / RAM_total), 2)*100
    res = {
        "ram_total": RAM_total,
        "ram_used": RAM_used,
        "ram_usage": RAM_usage,
    }
    return res


# Return % of CPU free %
def getCpuFree():
    return(str(os.popen("top -n1 | awk '/CPU/ {print $8}'").readline().strip()))

# Return runTime of system
def getRunTime():
    with os.popen("cat /proc/uptime") as ps:
        res = ps.readline().strip().split(" ")
    return res[0]
    pass

# 获取硬盘总量 kb
def getHardDiskTotal():
    with os.popen("df | awk '{print $2}'") as ps:
        res = ps.read().strip().split("\n")
    int_list = [(int(i)) for i in res[1:]]
    return sum(int_list)
    pass

# 获取硬盘使用量 kb
def getHardDiskUsed():
    with os.popen("df | awk '{print $3}'") as ps:
        res = ps.read().strip().split("\n")
    int_list = [(int(i)) for i in res[1:]]
    return sum(int_list)
    pass

# 获取硬盘的使用率 %
def getHardDiskUseAge():
    df_total = getHardDiskTotal()
    df_used = getHardDiskUsed()
    return round(df_used/df_total, 4)*100

# 获取当前sd卡容量(M)
def getSdMemory():
    sd_memory = None
    with os.popen("df | awk '{print $3}'") as ps:
        res = ps.read().strip().split("\n")
    return sd_memory


if __name__ == '__main__':
    pass




